﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace QDasConverter.Utils
{
    public class SocketHost
    {
        int port = 10080;
        Socket socket;
        IPEndPoint point;
        bool isConnected = false;

        public SocketHost(int port)
        {
            this.port = port;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
        }

        /// <summary>
        /// 监听指定的端口。
        /// </summary>
        public void Listen()
        {
            Thread thread = new Thread(new ThreadStart(listen));
            thread.IsBackground = true;
            thread.Start();
        }

        public void listen()
        {
            if (isConnected)
                return;

            try
            {
                socket.Bind(point);
                socket.Listen(10);
                isConnected = true;
                while (true)
                {
                    Socket connfd = socket.Accept();
                    Console.WriteLine("[服务器]Accept");
                    //byte[] readBuff = new byte[1024];
                    //int count = connfd.Receive(readBuff);
                    //string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
                    //Console.WriteLine("[服务器接收]" + str);

                    //byte[] bytes = System.Text.Encoding.Default.GetBytes("serv echo" + str);
                    //connfd.Send(bytes);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            isConnected = false;
        }
    }
}
